﻿using System;
using System.Diagnostics;
using System.IO;

namespace HB.Base
{
    /// <summary>
    /// 命令行执行封装
    /// </summary>
    public static class CmdHelper
    {
        /// <summary>
        /// 执行命令行输入
        /// </summary>
        /// <param name="shellCommand"> 命令行输入内容 </param>
        /// <param name="IsAdmin"> 是否管理员启动 </param>
        /// <returns> 执行后，命令行输出信息 </returns>
        public static string ExecShellForResult(string shellCommand)
        {
            if (string.IsNullOrEmpty(shellCommand))
            {
                throw new ArgumentNullException("shellCommand");
            }

            string ret = string.Empty;

            // 实例一个process类
            using (Process process = new Process())
            {
                // 设定程序名
                process.StartInfo.FileName = "cmd.exe";

                // 关闭Shell的使用
                process.StartInfo.UseShellExecute = false;

                // 重新定向标准输入，输入，错误输出
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                // 设置cmd窗口不显示
                process.StartInfo.CreateNoWindow = true;

                // 开始
                process.Start();

                // 输入命令，退出
                process.StandardInput.WriteLine(shellCommand);
                process.StandardInput.WriteLine("exit");

                // 获取结果
                ret = process.StandardOutput.ReadToEnd();

                return ret;
            }
        }


        /// <summary>
        /// 以管理员方式运行程序
        /// </summary>
        /// <param name="ExecutablePath">可执行文件路径</param>
        /// <param name="KillMySelf">是否结束自身</param>
        /// <param name="IsAdmin">是否管理员启动</param>
        /// <param name="Paramters">运行参数</param>
        public static void RunProcess(string ExecutablePath, bool IsAdmin = false, string Paramters = null, bool KillMySelf = false)
        {
            ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Path.GetDirectoryName(ExecutablePath);
            startInfo.FileName = ExecutablePath;
            startInfo.Arguments = Paramters;
            if (IsAdmin)
            {
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
            }

            try
            {
                Process.Start(startInfo);
                if (KillMySelf)
                {
                    Process.GetCurrentProcess().Kill();
                }
            }
            catch
            {
                return;
            }
        }
    }
}
